import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { OrgImage } from './models/orgImage.entity';
import { DeepPartial, Repository } from 'typeorm';
// Repository是一个提供数据库操作的工具库
@Injectable()
export class OrgImageService {
  // 注入OrgImage实体
  constructor(
    @InjectRepository(OrgImage)
    private OrgImageRepository: Repository<OrgImage>,
  ) {}

  // 删除用户
  async deleteByOrg(id: string,): Promise<boolean> {
    const imgs = await this.OrgImageRepository.createQueryBuilder('orgImage')
      .where(`orgImage.orgIdForFrontId = '${id}'`)
      .orWhere(`orgImage.orgIdForRoomId = '${id}'`)
      .orWhere(`orgImage.orgIdForOtherId = '${id}'`)
      .getMany();
    // console.log('res', res);
    if (imgs.length ===0) {
      return true;
    }
    const delResult = await this.OrgImageRepository.delete(imgs.map((item)=>{return item.id}))

    if(delResult?.affected > 0){
      return true
    }
    return false;
  }
  // 返回值是promise对象
  // DeepPartial是一个将实体（OrgImage）内部的所有属性加上?，即可以省略
  /**
   * 创建一个门店
   * @param entity
   * @returns
   */
  async create(entity: DeepPartial<OrgImage>): Promise<boolean> {
    // const res = await this.OrgImageRepository.insert(entity);//insert方法不会触发create事件
    const res = await this.OrgImageRepository.save(
      this.OrgImageRepository.create(entity), //create仅仅是创建一个内存实体，没有放入数据库
    ); //
    // console.log('res', res);
    if (res) {
      return true;
    }
    return false;
  }
  // 查询
  async findById(id: string): Promise<OrgImage | null> {
    const res = await this.OrgImageRepository.findOne({
      where: {
        id: id,
        // ...entity
      },
    });
    // console.log('res', res);
    return res;
  }
  // 修改
  async updateById(
    id: string,
    entity: DeepPartial<OrgImage>,
  ): Promise<boolean> {
    const existEntity = await this.findById(id);
    if (!existEntity) {
      return false;
    }
    Object.assign(existEntity, entity);
    // const res = await this.OrgImageRepository.update(id, entity);//这里update方法是不会触发entity的update事件的
    const res = await this.OrgImageRepository.save(existEntity); //需要使用save
    // console.log('res', res);
    if (res) {
      return true;
    }
    return false;
  }

}
